import React, { Fragment, LegacyRef, useCallback, useEffect, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import { Link, useNavigate } from 'react-router-dom';
import { Button, Form, Input, SpinLoading, Toast } from 'antd-mobile';
import { rules } from '@/utils/rules';
import type { FormInstance } from 'antd-mobile/es/components/form';
import { bindMobileLogin, qqLogin, sendCodeThunk } from '@/store/modules/loginStore';
import { useEnhanceDispatch } from '@/hooks';
import useCountdown from '@/hooks/useCountdown';
import type { BindMobileParams, QQLoginParams } from '@/type/LoginType';
import './LoginCallback.scss';

const LoginCallback = () => {
  const navigate = useNavigate();
  const enhanceDispatch = useEnhanceDispatch();
  // 表单组件实例
  const [formInstance] = Form.useForm<LegacyRef<FormInstance> | undefined>();
  // 自定义的倒计时hooks
  const { timeId, countdown, start, setStart, subCountdown, setCountdown } = useCountdown(60);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // qq登录的参数
  const [qqLoginParams, setQqLoginParams] = useState<QQLoginParams>({} as QQLoginParams);
  // 是否绑定手机
  const [bindingFlag, setBindingFlag] = useState<boolean>(true);
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>优医问诊 登录</span>), []);
  // 右边插槽内容
  const right = useCallback(() => (<Link to="/login">登录</Link>), []);

  /**
   * 获取验证码的回调函数
   * */
  const handleSendCode = async () => {
    try {
      await enhanceDispatch(sendCodeThunk({ mobile: formInstance.getFieldValue('mobile'), type: 'bindMobile' })).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description qq登录的回调函数
   * */
  const handleQQLogin = () => {
    if (!QC.Login.check()) return;
    QC.api('get_user_info').success((result: any) => {
      const info = { avatar: result.data.figureurl, nickname: result.data.nickname };
      QC.Login.getMe(async (openId: string, accessToken: string) => {
        try {
          const auth = { openId: openId, source: 'qq' };
          const newQQloginParams = Object.assign(info, auth);
          setQqLoginParams({ ...qqLoginParams, openId: newQQloginParams.openId });
          await enhanceDispatch(qqLogin(newQQloginParams)).unwrap();
          Toast.show({ icon: 'success', content: 'QQ登录成功' });
          navigate('/');
        } catch (rejectedValueOrSerializedError: any) {
          setBindingFlag(false);
          Toast.show(rejectedValueOrSerializedError);
        }
      });
    });
  };

  /**
   * @description 点击发送验证码按钮的回调函数
   * */
  const sendCode = () => {
    formInstance.validateFields(['mobile']).then(async result => {
      await handleSendCode();
      subCountdown();
    }).catch(error => {
      const message = error.errorFields[0].errors[0];
      Toast.show(message);
    });
  };

  /**
   * @description 提交表单且数据验证成功后触发的回调函数
   * */
  const handleFinsh = async (values: BindMobileParams) => {
    try {
      setLoading(true)
      const newBindMobileParams = { ...values, openId: qqLoginParams.openId };
      await enhanceDispatch(bindMobileLogin(newBindMobileParams)).unwrap();
      Toast.show({ icon: 'success', content: '绑定手机成功' });
      navigate('/');
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }finally {
      setLoading(false)
    }
  };

  /**
   * @description 提交表单且数据验证失败后触发的回调函数
   * */
  const handleFinishFailed = (error: any) => {
    const message = error.errorFields[0].errors[0];
    Toast.show(message);
  };

  const renderBindForm = () => {
    if (!bindingFlag) {
      return (
        <Fragment>
          {/*导航栏组件*/}
          <NavBar back={left()} right={right()}></NavBar>
          {/*绑定头部*/}
          <div className="login-callback-header">
            <div className="left">
              <h3>手机绑定</h3>
            </div>
          </div>
          {/*绑定表单*/}
          <Form mode="card" form={formInstance} hasFeedback={false} onFinish={handleFinsh} onFinishFailed={handleFinishFailed}>
            <Form.Item name="mobile" rules={rules.mobile}>
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item name="code" rules={rules.code} extra={<a onClick={sendCode}>{start ? `${countdown}秒后重新获取` : '发送验证码'}</a>}>
              <Input type="text" placeholder="请输入短信验证码" />
            </Form.Item>

            <Form.Item className="last">
              <Button loading={loading} color="primary" type="submit">立即绑定</Button>
            </Form.Item>

          </Form>
        </Fragment>
      );
    } else {
      return (
        <div className="lazyLoading">
          <SpinLoading color="primary" />
          <span>QQ登录中</span>
        </div>
      );
    }
  };

  useEffect(() => {
    handleQQLogin();
  }, []);

  return (
    <div className="login-callback">
      {
        renderBindForm()
      }
    </div>
  );
};

export default LoginCallback;